import * as jwt from 'jsonwebtoken';
import * as OSS from 'ali-oss';
import { Context } from 'egg';
import {IRetbody} from '../entity/retBody'

export class StatusError extends Error {
  status: number;
  code: number;
  constructor (message: string, status: number, code: number) {
    super(message);
    this.status = status;
    this.code = code;
  }
}

// 扩展一些框架便利的方法
export default {
  // 登录用户
  get user(this: Context) {
    const token: string = this.request.headers['authorization'];
    if (!token) {
      return '';
    }
    let user;
    try {
      user = jwt.verify(token, this.app.config.jwtSecret);
    } catch (error) {
      user = '';
    }
    return user;
  },
  get userId(this: Context) {
    const userId: number = this.user ? this.user.id : 0;
    return userId;
  },
  get alioss(this: Context) {
    const oss = new OSS({
      region: this.app.config.alioss_config.region,
      accessKeyId: this.app.config.alioss_config.accessKeyId,
      accessKeySecret: this.app.config.alioss_config.accessKeySecret,
      bucket: this.app.config.alioss_config.bucket,
    });
    return oss;
  },
  /**
   * 用法 this.ctx.validate(rule, data)
   * @param {string，object} rule 校验规则
   * @param {object} data 需要校验的数据
  */
  // validate(rule, query) {
  //     const validator = new AsyncValidator(descriptor)
  //     let validateResult = true
  //     validator.validate(query, { firstFields: true }, errors => {
  //       if (errors) {
  //         validateResult = false
  //         if (this.app.config.validatePlus
  //           && this.app.config.validatePlus.resolveError
  //           && typeof this.app.config.validatePlus.resolveError === 'function') {
  //           this.app.config.validatePlus.resolveError(this, errors)
  //         } else {
  //           this.type = 'json';
  //           this.status = 400;
  //           this.body = {
  //             code: 400,
  //             message: '参数错误',
  //             error: errors
  //           }
  //         }
  //       }
  //     })
  //     return validateResult;
  // },
  ok(this: Context, data?: object | null, message: string = 'success') {
    this.status = 200;
    this.body = {
      code: 200,
      data,
      msg: message
    } as IRetbody;
  },
  fail (this: Context, message: string, code: number = 10001, status: number = 200,  ) {
    throw new StatusError(message, status, code);
  },
};